
const Utils = {}

/**
 * 根据数组的 sort 字段排序
 * @param {Array} data
 */
Utils.sortByOrder = (data = []) => {
  if (!Array.isArray(data)) {
    return data
  }
  function sortByOrderChildren(source) {
    // 递归排序子元素
    for (let i = 0; i < source.length; i += 1) {
      const children = source[i].children
      source[i].title = source[i].permissionName
      if (children && children.length > 0) {
        source[i].children = sortByOrderChildren(children)
      }
    }
    return source.sort(function(obj1, obj2) {
      var val1 = obj1['sort']
      var val2 = obj2['sort']
      if (val1 < val2) {
        return -1
      } else if (val1 > val2) {
        return 1
      } else {
        return 0
      }
    })
  }
  return sortByOrderChildren(data)
}

export default Utils
